<template>
  <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="选择课程" prop="course">
        <el-transfer v-model="dataForm.course" :data="cList" :titles="['全部课程', '已选择']"
                     :props="{key: 'id',label: 'name'}"></el-transfer>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {fetchCourseList} from '@/api/teacher/course'
import {addObj, putObj, getObj} from '@/api/student/coursestudent'

export default {
  data() {
    return {
      visible: false,
      canSubmit: false,
      dataForm: {
        id: 0,
        course: []
      },
      cList: [],
      dataRule: {}
    }
  },
  created() {
    this.getCourseList()
  },
  methods: {
    getCourseList() {
      fetchCourseList().then(response => {
        console.log(response.data)
        this.cList = response.data
      })
    },
    init(id) {
      this.dataForm.studentId = id || 0;
      this.visible = true;
      this.canSubmit = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        getObj(id).then(response => {
          response.data.forEach(item => {
            this.dataForm.course.push(item.courseId)
          })
        })
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          if (this.dataForm.id) {
            putObj(this.dataForm).then(data => {
              this.$notify.success('修改成功')
              this.visible = false
              this.$emit('refreshDataList')
            }).catch(() => {
              this.canSubmit = true;
            });
          } else {
            addObj(this.dataForm).then(data => {
              this.$notify.success('添加成功')
              this.visible = false
              this.$emit('refreshDataList')
            }).catch(() => {
              this.canSubmit = true;
            });
          }
        }
      })
    }
  }
}
</script>
